<template>
  <div v-loading="state.loading" class="bg-gray pd0 gap20 flex-column">
    <div class="top bg-white flex pd10" style="gap: 12px">
      <OverviewFactory title="客户情况" :data="state.agentData" />
      <OverviewAgent title="代理情况" :data="state.agentData" />
      <OverviewAll title="综合数据" :data="state.agentData" />
    </div>

    <div class="top bg-white flex-column gap10 pd10">
      <div class="bold fs16">故障概览</div>
      <div class="flex1 flex-row-center-between gap20">
        <DescItem title="本月发生故障" :count="state.faultData.currentMonthFaultCount" :link="true" path="/fault/list" :query="{ ...getCurrentMonth() }" />
        <DescItem title="环比增长" :count="state.faultData.faultSequentialGrowth" :show-unit="false" />
        <DescItem title="同比增长" :count="state.faultData.faultYearOnYearGrowth" :show-unit="false" />
        <DescItem title="故障客户家数" :count="state.faultData.currentMonthFaultCustomerCount" />
      </div>
      <div class="flex1 flex-row-center-between gap20">
        <DescItem
          title="本月故障最多客户"
          :link="true"
          icon-name="factory"
          path="/fault/list"
          :query="{ customerName: state.faultData.currentMonthFaultMaxCustomer, ...getCurrentMonth() }"
          :count="state.faultData.currentMonthFaultMaxCustomer"
          :show-unit="false"
        />
        <DescItem
          title="本月故障最多部件"
          path="/fault/list"
          icon-name="home-part"
          :query="{ faultDeviceCode: state.faultData.currentMonthFaultMaxDevice, ...getCurrentMonth() }"
          :link="true"
          :count="state.faultData.currentMonthFaultMaxDevice"
          :show-unit="false"
        />
        <DescItem
          title="本月故障最多产品型号"
          icon-name="home-xh"
          path="/fault/list"
          :query="{ productionNumber: state.faultData.currentMonthFaultMaxProductionNumber, ...getCurrentMonth() }"
          :link="!!state.faultData.currentMonthFaultMaxProductionNumber"
          :count="state.faultData.currentMonthFaultMaxProductionNumber ? state.faultData.currentMonthFaultMaxProductionNumber : '（无产品型号数据）'"
          :show-unit="false"
        />
        <div class="pd10 flex1"></div>
      </div>
    </div>
    <div ref="boxEl" class="flex1 bg-white pd10" style="overflow: hidden">
      <VxeTableVue
        ref="tableEl"
        :table-height="state.tableHeight"
        :column-config="columnConfig"
        :query-form-data="{ params: { hasUser: '0' } }"
        data-list-api="/customer/page"
        :show-top-add-btn="false"
        :show-top-del-btn="false"
        :show-del-btn="false"
        :show-table-top-right="false"
        :show-pagination="false"
        :show-top-right-icon="false"
      >
        <template #topExtra="{ selectedList }">
          <div class="flex-row-center-between width-all">
            <div>
              <span>待维护服务人员</span>
              <span class="mgr30 mgl30 grey-text">共计{{ tableEl?.total }}条</span>
            </div>
            <el-button v-has-permi="['coustomer-maintain-user']" type="primary" @click="handleMaintainUser(selectedList, 'batch')">维护服务人员</el-button>
          </div>
        </template>

        <template #extraBtn1="{ row }">
          <el-button v-has-permi="['coustomer-maintain-user']" type="primary" link @click="handleMaintainUser([row], 'single')">维护服务人员</el-button>
        </template>
      </VxeTableVue>
    </div>

    <!------------------------------------------ 维护人员弹窗 ------------------------------------------------------->

    <DialogVue ref="dialogEl" title="维护服务人员" :width="500" :form-data="state.maintainFormData" @before-submit="onBeforeSubmit">
      <SelectVue v-model="state.selectedUsers" :transfer="false" multiple option-api="/auth/role/getUserByRoleName" :query-params="{ roleName: '服务人员' }" />
    </DialogVue>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import dayjs from 'dayjs'
  import { VxeTableVue, type VxeTableViewInstance } from '@/components/table'
  import DialogVue, { type DialogVueInstance } from '@/components/dialog'
  import SelectVue from '@/components/select'
  import DescItem from './cpns/desc-item.vue'
  import OverviewFactory from './cpns/overview-factory.vue'
  import OverviewAgent from './cpns/overview-agent.vue'
  import OverviewAll from './cpns/overview-all.vue'
  import { columnConfig, type FaultData, type AgentData, type ICustomerEntity } from './config'
  import request from '@/service'
  import { Ui } from '@/utils'

  const boxEl = ref<HTMLDivElement>()

  const tableEl = ref<VxeTableViewInstance>()
  const dialogEl = ref<DialogVueInstance>()

  interface IMaintainFormData {
    customerIds: string[]
    userIds: string[]
  }

  const state = reactive({
    loading: false,
    tableHeight: 0,
    faultData: {} as FaultData,
    agentData: {} as AgentData,

    maintainFormData: {
      customerIds: [],
      userIds: []
    } as IMaintainFormData,
    selectedUsers: [] as string[]
  })

  /**----------------------------methods----------------------------------------------------------------------- */

  const getCurrentMonth = () => {
    const today = new Date()
    const currentMonth = today.getMonth()
    const currentYear = today.getFullYear()
    const startTime = new Date(currentYear, currentMonth, 1)
    const endTime = new Date(currentYear, currentMonth + 1, 0)

    return {
      faultDiscoveryStartTime: dayjs(startTime).format('YYYY-MM-DD'),
      faultDiscoveryEndTime: dayjs(endTime).format('YYYY-MM-DD')
    }
  }

  /**
   * 维护服务人员
   */
  const handleMaintainUser = (customers: ICustomerEntity[], type: 'batch' | 'single') => {
    if (type === 'batch' && !customers.length) return Ui.useMessage('warning', '请先勾选需要维护的数据')

    state.maintainFormData.customerIds = customers.map(item => item.id)
    state.selectedUsers = type === 'batch' ? [] : customers[0].userList.map(item => item.id)
    dialogEl.value?.handleOpen()
  }

  /**
   * 提交服务人员
   */
  const onBeforeSubmit = (data: IMaintainFormData, fn: any) => {
    fn(false)
    state.maintainFormData.userIds = state.selectedUsers

    const handleConfirm = () => {
      request.put('/customer/update', state.maintainFormData).then(res => {
        if (res.code !== 0) return Ui.useMessage('error', res.msg)
        dialogEl.value?.handleClose()
        reflesh()
      })
    }

    if (state.selectedUsers.length) return handleConfirm()

    Ui.useMessageBox({
      text: '未选择服务人员，保存后将把原有的服务人员移除，确定保存？”，点击确定后，将所选客户的服务人员清空',
      handleConfirm
    })
  }

  const reflesh = () => {
    tableEl.value?.query()
  }

  const getFaultData = () => {
    request.get<FaultData>('/fault/statistics/index').then(res => {
      if (res.code !== 0) return Ui.useMessage('error', res.msg)
      state.faultData = res.data
    })
  }

  const getAgentData = () => {
    request.get<AgentData>('/agent/statistics/index').then(res => {
      if (res.code !== 0) return Ui.useMessage('error', res.msg)
      state.agentData = res.data
    })
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */
  getFaultData()

  getAgentData()

  onMounted(() => {
    state.tableHeight = boxEl.value!.clientHeight + 400
  })
</script>

<style scoped lang="less"></style>
